const mongoose = require('mongoose');
const {pagerHelper} = require("../util/PagerHelper.js");
//连接的数据库不需要先创建
mongoose.connect('mongodb://localhost/bookshop', {
    useUnifiedTopology: true,
    useNewUrlParser: true
});

//创建集合(表)规则，不是集合
const schema = new mongoose.Schema({
    name: String,
    price: Number,
    count: Number,
    createDate: {
        type: Date,
        default: Date.now,
    }
});

//创建集合(表)
const model = new mongoose.model("books", schema);

/**
 * 同步函数，分页查询书本
 * @param query 查询条件对象
 * @param columns   查询的字段名称
 */
async function findByPage(query, columns) {
    let result = await model.find(query).select(columns).limit(pagerHelper.pageSize).skip(pagerHelper.pageSize * (pagerHelper.pageNum - 1));
    // result.then(result => result)
    //     .catch(e => console.log(e))

    return result;
}

function querydb(query, columns) {
    return new Promise((resolve, rejected) => {
        model.find(query).select(columns).exec((err, data) => {
            if (err) {
                rejected(err);
            } else {
                resolve(data);
            }
        });
    })
}

module.exports = {
    findByPage, querydb, model
}